package com.desire.homework;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.concurrent.TimeUnit;

/**
 * @author desire
 */
public class _49_多线程售票_定时关机 {
    public static void main(String[] args) {
        /*
        //实现Runnable接口
        Tickets t = new Tickets(15);
        new Thread(new Tickets(15), "科学大道").start();
        new Thread(t, "东风路").start();
        new Thread(t, "火车站").start();
        new Thread(t, "撤销路").start();
        new Thread(t, "阿萨德路").start();
        new Thread(t, "是不是路").start();
        new Thread(t, "阿斯蒂路").start();


        */


        //多长时间后关机 5s
        new Thread(() -> {
            long t1 = System.currentTimeMillis();
            while (true) {
                long ok = System.currentTimeMillis() - t1;
                if (ok >= 5 * 1000) {
                    break;
                }
            }
            System.out.println("系统正在关机5...");
        }).start();
        //
        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(10);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("系统正在关机10");
        }).start();

        //指定时间关机 2021-1-30 21:30:00
        new Thread(() -> {
            String s = "2022-2-8 10:36:00";
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            long end = 0;
            try {
                end = sdf.parse(s).getTime();
            } catch (ParseException e) {
                e.printStackTrace();
            }
            try {
                TimeUnit.MILLISECONDS.sleep(end - System.currentTimeMillis());
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.printf("%s - 系统正在关机%n", s);
        }).start();


    }

    public static class Tickets implements Runnable {
        private int num = 100;

        public Tickets() {
        }

        public Tickets(int num) {
            this.num = num;
        }

        @Override
        public void run() {
            System.out.println("开始线程: " + Thread.currentThread().getName());
            while (true) {
                synchronized (this) {
                    if (num == 0) {
                        System.out.println("车票售卖完了");
                        break;
                    }
                    System.out.printf("%s:售出一张票，剩余%d张票%n", Thread.currentThread().getName(), --num);
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            System.out.println("线程结束");
        }
    }

}
